import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/model/patrol/patrol_task_model.dart';
import 'package:ls_work/sql/AppDbUtils.dart';
import 'package:ls_work/sql/app_data_base.dart';

import '../../sql/protral/offline_submit_patrol_entity.dart';

typedef UploadTaskListener = Function(
    int index, OfflineSubmitPatrolData record);

class OfflineTaskUploadService {
  static OfflineTaskUploadService? _instance;

  factory OfflineTaskUploadService.instance() =>
      _instance ??= OfflineTaskUploadService._();

  OfflineTaskUploadService._();

  var model = PatrolTaskModel();

  BuildContext? _context;

  void initContext(BuildContext context) {
    _context = context;
  }

  Future<Map<String, dynamic>> uploadSingleLocalRecord(
      OfflineSubmitPatrolData record) async {
    var result = await model.uploadLocalRecord(record);
    if (result['success']) {
      await AppDbUtils.instance().patrolTaskDao.deleteLocalRecord(record);
      return {"success": true};
    } else {
      return {"success": false, "msg": "${result['msg']},执行记录已保存本地"};
    }
  }

  Future<void> uploadRecordList(
      List<OfflineSubmitPatrolData> list, UploadTaskListener listener) async {
    for (var i = 0; i < list.length; i++) {
      var record = list[i];
      var data = await uploadSingleLocalRecord(record);
      listener(i + 1, record);
    }
  }
}

class UploadTaskDialog extends StatefulWidget {
  List<OfflineSubmitPatrolData> list;

  UploadTaskDialog({required this.list});

  @override
  State<StatefulWidget> createState() => _UploadTaskState();
}

class _UploadTaskState extends State<UploadTaskDialog> {
  var current = 0;
  var total = 1;
  var hasFinish = false;

  @override
  void initState() {
    super.initState();
    setState(() {
      total = widget.list.length;
    });
    OfflineTaskUploadService.instance().uploadRecordList(widget.list, (index, record) {
      setState(() {
        current = index;
      });
      eventBus.fire(SendMessageEvent(MessageConfig.REFRESH_PATROL));
      eventBus.fire(SendMessageEvent(MessageConfig.REFRESH_LOCAL_PATROL));
      if(current==total){
        Future.delayed(Duration(microseconds: 500),(){
          hasFinish = true;
          Go().pop();
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            "本地数据上传中",
            style: TextStyle(
                color: Colors.black, fontSize: 16, fontWeight: FontWeight.bold,decoration: TextDecoration.none),
          ),
          Container(height: 10,),
          LinearProgressIndicator(
            backgroundColor: Colors.grey,
            valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
            value: current/total,
          ),
          Container(height: 10,),
          Text(
            "正在上传第${current}条记录,共${total}条记录",
            style: TextStyle(
                color: Colors.black, fontSize: 16, fontWeight: FontWeight.normal,decoration: TextDecoration.none),
          ),

        ],
      ).addToContainer(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: 10.borderRadius
          ),
          width: MediaQuery.of(context).size.width - 60,
          padding: EdgeInsets.all(20)),
    );
  }
}
